import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/account_api.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/request/password_request.dart';
import 'package:sainbainu/common/repositories/account_repository.dart';
import 'package:sainbainu/common/utils/custom_exception.dart';
import 'package:sainbainu/common/utils/encrypt.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/values/constant.dart';

import 'index.dart';

class PasswordChangeController extends GetxController {
  PasswordChangeController();

  final state = PasswordChangeState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.passwdController = TextEditingController();
    state.passwdCheckController = TextEditingController();
    state.accountRepository = AccountRepository(AccountApi());
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.passwdController.dispose();
    state.passwdCheckController.dispose();
  }

  /// 确认提交
  void handleSubmit() async {
    try {
      if (state.passwdController.text.isEmpty) {
        throw CustomException('请输入新密码');
      }
      if (state.passwdController.text.length < AppConstant.pwdLength) {
        throw CustomException('密码至少${AppConstant.pwdLength}位字符');
      }
      if (state.passwdCheckController.text.isEmpty) {
        throw CustomException('请再次输入新密码');
      }
      if (state.passwdController.text != state.passwdCheckController.text) {
        throw CustomException('两次输入的密码不一致');
      }
      LoadingUtil.showLoading(text: '提交中...');
      await state.accountRepository.setPasswd(PasswordRequest(
        passwd: EncryptUtil.encrypt(state.passwdController.text),
        passwdCheck: EncryptUtil.encrypt(state.passwdCheckController.text),
      ));
      LoadingUtil.showSuccess('密码设置成功'.tr);
      Get.back();
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } on CustomException catch (e) {
      LoadingUtil.showError(e.toString());
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }
}
